package com.ruoyi.web.controller.demo.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.web.controller.tool.PdfUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * 表单相关
 *
 * @author lh
 */
@Controller
@RequestMapping("/temp")
public class TempController {
  @RequestMapping("/pdf")
  public void pdf(@RequestBody String paramsStr, HttpServletResponse response) {
    OutputStream out = null;
    try {
      JSONObject params = JSONObject.parseObject(paramsStr);
      String title = params.getString("title");
      String time = params.getString("time");
      JSONArray tableTitle = params.getJSONArray("tableTitle");
      com.alibaba.fastjson.JSONArray data = params.getJSONArray("data");
      String direction = params.getString("direction");
      ByteArrayOutputStream baos = PdfUtils.createPdf(title, time, data, tableTitle, direction);
      response.setHeader(
          "Content-Disposition",
          "attachment; filename="
              + new String((title + ".pdf").getBytes(), StandardCharsets.ISO_8859_1));
      response.setContentLength(baos.size());
      out = response.getOutputStream();
      baos.writeTo(out);
      out.flush();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        out.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }
}
